package com.tian.netty.core;

import com.tian.netty.executor.RequestExecutorBase;
import com.tian.netty.message.AbstractMsg;
import com.tian.netty.message.req.TestReq;
import com.tian.netty.util.JConverter;
import com.tian.netty.util.Utility;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * {@code @description:} 电桩请求分发器, 根据消息类型将请求分发到对应的业务处理类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-03-10 14:41
 * {@code @version:} 1.0
 */
@Slf4j
public class ReqDispatcher {

    private static final int MAX_THREAD_NUM = 8;

    private static final ExecutorService executorService = Executors.newFixedThreadPool(MAX_THREAD_NUM);

    public static void submit(SocketChannel channel, byte[] msgObject) {
        //拿到对应的bean
        String beanName = "MSG_" + (msgObject[1] & 0xFF);
        //bean注入是名称指定清楚
        RequestExecutorBase executor = Utility.getBean(beanName, RequestExecutorBase.class);

        if (executor != null) {
            executor.setChannel(channel);
            executor.setMsgObject(msgObject);
            executorService.submit(executor);
        } else {
            log.error("invalid request=>[from : " + channel.remoteAddress() + ", message : " + JConverter.bytes2String(msgObject) + "]");
        }
    }
}
